<?php
session_start();
$_SESSION["previouspage"] = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];//remembers the url of this page, used for redirect.

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
	header('Location: ./');
}
$paperId = (int)$_GET['id'];
$_SESSION["paperid"] = $paperId;
$_SESSION["bibtexid"] = $paperId;

require_once 'include/config.lib.php';
require_once 'include/database.lib.php';
require_once 'include/tags.php';

ConnectToDB();// Connect to the DB.

// Load summary data about the paper.
$paperReq = DBExecute('	SELECT title, abstract, b.authors as authors, rating.* FROM bibtex AS b
						LEFT JOIN (
						SELECT r.bibtexid, AVG(rr.clarity) AS clarity, AVG(rr.structure) AS structure,
							AVG(rr.novelty) AS novelty, AVG(rr.usefulness) AS usefulness, AVG(rr.total) AS total
						FROM resource AS r, rateresource AS rr '.
						/*LEFT JOIN authoring ON authoring.resourceid=rr.resourceid
						LEFT JOIN person ON person.id=authoring.personid*/
							'WHERE r.id=rr.resourceid AND r.bibtexid=? 
							
							GROUP BY r.bibtexid
						) AS rating ON b.id=rating.bibtexid
						WHERE b.id=?', array($paperId, $paperId));

$paper = $paperReq->fetchAssocRow();
$ratings = array($paper['USEFULNESS'] * 20, $paper['STRUCTURE'] * 20, $paper['CLARITY'] * 20, $paper['NOVELTY'] * 20, $paper['TOTAL'] * 20);
//Note that the ratings are multiplied by an extra factor of 2. This is a hack to get the rating graph to display properly.


//resource IDs associated with the bibtexid
$resourceIDs = DBExecute(' SELECT r.id AS resourceID FROM resource r
						 WHERE r.bibtexid = ?', array($paperId));

$authorsReq = DBExecute(' SELECT unique p.name AS author FROM person p, authoringbib a
						WHERE a.bibtexid = ? AND a.personid = p.id', array($paperId));

$personName = "";
$userName = "";
$personID = "";
$userIsAuthor = false;

if(isset($_SESSION["accountNo"])){
    //get the user's username
	$userName = $_SESSION["accountNo"];
    
    //get the user's real name
    $name = DBExecute('SELECT person.name AS name
                        FROM person WHERE person.username = ?', $userName); //actual name
	$personNameRow = $name->fetchAssocRow();
	$personName = $personNameRow['NAME'];	
    
    //get the user's personID
    $ID = DBExecute('SELECT person.id AS id 
						FROM person WHERE person.username = ?', $userName);
	$personIDRow = $ID->fetchAssocRow();
	$personID = $personIDRow['ID'];
}

$authors = '';	//authors of the publication
while ( $keyrow = $authorsReq->fetchAssocRow()) {
	$authors .= $keyrow['AUTHOR'] . '; ';
	
	if($keyrow['AUTHOR'] == $personName)  // check if the user is alrerady listed as an author
		$userIsAuthor = true;	
} 



?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/template.css" />
<link rel="stylesheet" type="text/css" href="css/paper_view.css" />
<link rel="stylesheet" type="text/css" href="css/conv_styles.css" />
<link rel="stylesheet" type="text/css" href="css/network_styles.css" />
<link rel="stylesheet" type="text/css" href="third_party/jquery-ui-1.8.5/jquery-ui-1.8.5.custom.css" />
<!-- third party scripts -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="third_party/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="third_party/jquery-ui-1.8.5/jquery-ui-1.8.5.custom.min.js"></script>
<script type="text/javascript" src="third_party/jit.js"></script>
<!--[if IE]><script language="javascript" type="text/javascript" src="third_party/excanvas.js"></script><![endif]-->
<!-- project specific scripts -->
<script type="text/javascript" src="js/system.js"></script>
<script type="text/javascript" src="js/timechart.js"></script>
<script type="text/javascript" src="js/conversation.js"></script>
<script type="text/javascript" src="js/network.js"></script>
<script type="text/javascript" src="js/network_custom.js"></script>
<script type='text/javascript'>
var paperId = <?php echo $paperId; ?>;
var commentsWidget = null;
var networkWidget = null;
var timechartWidget = null;

function Toggle(showId, hideId) {
	document.getElementById(showId).style.display = "block";
	document.getElementById(hideId).style.display = "none";
}

function GInitialize() {
	timechartWidget = new TimeChart(document.getElementById("timeline-section"),
																	{ link: 'javascript:commentsWidget.highlightComment({id})' });
	RequestData("data.php", { "requestType": "timechart", "id": paperId }, timechartWidget.update);
}

google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(GInitialize);

function FilterByPeople(peopleIds) {
	commentsWidget.filterThreadsByPeople(peopleIds);
	timechartWidget.filterByPeople(peopleIds);
}

function OnLoad() {
	commentsWidget = new Comments(document.getElementById("comments-container"));
	RequestData("data.php", { "requestType": "commentTree", "id": paperId }, commentsWidget.update_comments);
	networkWidget = new Network("network", FilterByPeople, new NetworkCustom('paper'));
	RequestData("data.php", { "requestType": "relationships", "id": paperId }, networkWidget.update);
}

$(function() {  //Tabs must be declared here
	$("#tabs").tabs();
});
</script>
<title>Paper Review - CoRAL Reporter</title>
</head>
<body onload="OnLoad();">
<?php //to determine whether a user has logged in or not, which will output different buttons
if(isset($_SESSION["accountNo"]))	
{	
	$inorout = "controller/logout.php";	
	$display = "Log out";
}
else
{	
	$inorout = "login.php";
	$display = "Log in";
}
?>
	<div id="body-wrapper">
		<?php include_once 'static/header.php'; ?>
		<div id="body">
			<!-- START SECTION: summary -->
			<div id="summary-section" class="section">	
					<img id="rating-chart" src="http://chart.apis.google.com/chart?cht=bhs&chs=250x120&chxt=x,y&chd=t:<?php echo implode(',', $ratings); ?>&chxl=0:|0|1|2|3|4|5|1:|usefulness|structure|clarity|novelty|total&chbh=15" />
					<!--Note: for information on how to create/modify the ratings chart, visit: http://code.google.com/apis/chart/docs/chart_wizard.html-->
				<table id="stat" class="info"> <!-- summery information for the top of the page (title, abstract, authots, keywords -->
					<tr>
						<td><h1><?php echo isset($paper['TITLE']) ? htmlentities($paper['TITLE']) : 'Title not available'; ?></h1></td>
					</tr>
					<tr>
						<td><?php echo isset($paper['ABSTRACT']) ? htmlentities($paper['ABSTRACT']) : htmlentities($paper['URL']); ?></td>
					</tr>
					<tr></tr>
					<tr>
						<td><?php $keywords = getPaperKeywords($paperId);
						 echo (isset($keywords) && $keywords != '') ? '<b>Keywords: </b> '.htmlentities($keywords)	: '<b>Keywords: </b> - '; ?>
						</td>
					</tr>
					<tr>
						<td>
						<b>Author(s): </b>
							<?php 	
							if(isset($_POST['SubmitCheck']) && ($userIsAuthor == false)){ 	//If a user was added to the authors, add them to the displayed authors
								$authors .= " " . $personName;
								/*if(isset($paper['AUTHORS']) && $paper['AUTHORS'] != ''){
									($paper['AUTHORS']) .= " " . $personName;
									echo 'author added <br/>';
								}
								else echo 'authors not set <br/>';*/
							}
							echo (isset($paper['AUTHORS'])  && $paper['AUTHORS'] != '') ? htmlentities($paper['AUTHORS']) : (isset($authors['AUTHOR']) ? htmlentities($authors) : ' - '); 
							?>				
						</td>
					</tr>
					<tr>
					</tr>
				</table>
			</div>
			
			<?php 


				$fileloc = DBExecute(' SELECT b.uploadpath AS path FROM bibtex b
						WHERE b.id = ?', array($paperId));	//The location of an uploaded file associated paper, if it exists
				$file_location = $fileloc->fetchAssocRow();
				$target_path = $file_location['PATH'];
				$target_path = "../" . $target_path;
				$split = explode(".",$target_path);
				$extension = $split[count($split)-1];
			?>
			<div id="links-section" class="section">	<!-- space below the summery section that displays the links (claim paper, add to watch list, print report etc -->
	
				<a class = "section" onclick="javascript:showElement('claimpaper')"><u>Are you an author of this publication?</u></a>&nbsp;&nbsp;&nbsp;&nbsp;
				<div id="claimpaper" style="display:none" class = "section">
					<?php
		
					if(isset($_SESSION["accountNo"])){	//check if user is signed in
		 				if(isset($_POST['SubmitCheck'])) {	//Test if the form has already been submitted
							if($userIsAuthor == false) {	//check if the user is already listed as an author
								$resourceID = '';
								
								/*while ( $row = $resourceIDs->fetchAssocRow()) {
								$resourceID = $row['RESOURCEID'];
								 */
								$insert = DBExecute("INSERT INTO authoringbib (personid,bibtexid)
													VALUES (?, ?)", array($personID, $paperId));
								/*}*/
					         	echo "You have been added as an author of this publication with this username. 
					         	<br/> If your name is not listed in the authors list of the paper, you should also update the citation information in the neighbor tab.";
							}
					     	else{
					     		echo "You are already listed as an author of this publication with this username. 
					     		<br/> If your name is not listed in the authors list of the paper, you should also update the citation information in the neighbor tab.";
					     	}
		 				}
		
						?>
						<form id="claimPub" action="<?=$SERVER["PHP_SELF"]?>" method="post">
							<tr><th> Add your name the list of authors:</td></tr>
							<input type="hidden" name="SubmitCheck" value="sent">
							<input type="submit" class="button" value="Claim Paper" />
						</form>
						<?php		
					}
					else {
						echo 'Please sign in to claim a paper';
					}
					?>
				</div>
				
				<?php
				if($file_location['PATH'] != NULL && $file_location['PATH'] != "../upload/"){ 
				?>
					<a href="controller/downloadpaper.php?file=<?php echo $target_path ?>&properFilename=DownloadedPaper&extension=<?php echo $extension ?>">Download Paper</a>&nbsp;&nbsp;&nbsp;&nbsp;
				<?php
				}
				?>

					<a href="controller/addwatchlist.php">Add to watch list</a>&nbsp;&nbsp;&nbsp;&nbsp;
					<a href="controller/createreport.php">Print Report</a> &nbsp;&nbsp;&nbsp;&nbsp;

				<!-- Facebook Like -->
<!--				<iframe src="http://www.facebook.com/plugins/like.php?href&amp;send=false&amp;layout=button_count&amp;width=450&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font=arial&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>-->

			</div>
			
			<!-- END SECTION: summary -->
			
			<div id="details-section" class="section">
				<div id="tabs" style="overflow:hidden;">
					<ul> 
						<li><a href="#tabs-1"><strong>Overview</strong></a></li>
						<li><a href="#tabs-2"><strong>Citation Information</strong></a></li>
					</ul>
					<div id="tabs-1"> <!-- first tab on the paperview page - Overview -->
					<fieldset>
						<!--<span>Time Line</span>
						-->
						<legend>Time Line    
						<!--<div style="float:right;">-->
						<a href="help.php#timeline" onClick="return popup(this, 'notes')"><img alt="help" src="image/question.png" /></a>
						
						
						</legend>
						<!-- START SECTION: timeline -->
						<div id="timeline-section" class="section">
							<div id="timeline-chart"></div>
						</div>
						<!-- END SECTION: timeline -->
					</fieldset>
						
						<!-- START SECTION: social graph -->
						
					<fieldset class="left-section">
					<legend>Reviewers Network
					<a href="help.php#network" onClick="return popup(this, 'notes')"><img alt="help" src="image/question.png" /></a> 
					</legend>
						<div id="network-section" class="left-section">
							<div id="network">
								
							</div>
						</div>
					</fieldset>
						<!-- END SECTION: social graph -->
						
						<!-- START SECTION: filters -->
						<div id="filter-section" class="right-section">
						<fieldset>
						<legend>Tags</legend>
						<div id="filter">
							<?php $tags = getPaperTags($paperId);?>
							<div id="tags-simple" class="tags">
								<ul>
									<?php
									// Show top 5 tags.
									$count = 0;
									foreach ($tags as $tag => $freq) {
										$tag = htmlentities($tag);
										echo '<li><a href="tag_papers.php?label=',urlencode($tag),'">', $tag, '</a></li>';
										$count++;
										if ($count == 5) break;
									} ?>
									<li class="highlight"><a href="javascript:Toggle('tags-full', 'tags-simple')">expand</a></li>
								</ul>
							</div>
							<div id="tags-full" class="tags">
								<ul> 
									<?php
									foreach ($tags as $tag => $freq) {
										$tag = htmlentities($tag);
										echo '<li class="tag', $freq, '"><a href="tag_papers.php?label=',$tag,'">', $tag, '</a></li>';
									} ?>
									<li class="highlight"><a href="javascript:Toggle('tags-simple', 'tags-full')">collapse</a></li>
								</ul>
							</div>
						</div>
						</fieldset>
						</div>
						<!-- END SECTION: filters -->
						
						<!-- START SECTION: threaded control -->
						
						
						<div id="comment-section" class="right-section">
						
						<fieldset>
						<legend>Discussions
						<a href="help.php#comments" onClick="return popup(this, 'notes')"><img alt="help" src="image/question.png" /></a>
						</legend>
						
							<ul class="horizontal" id="sort-by">
										
								<li style="padding-right:1px; padding-left: 5px; margin-left: 15px; margin-right: 0px;"><b>Sort by:</b></li>
								<li><input type="radio" name="sort" onChange="commentsWidget.changeSort(commentsWidget.sort_enum.byNameAsc)">Names</li>								
								<li><input type="radio" name="sort" onChange="commentsWidget.changeSort(commentsWidget.sort_enum.byDateDesc)">Recent first</li>
								<li><input type="radio" name="sort" onChange="commentsWidget.changeSort(commentsWidget.sort_enum.byDateAsc)">Recent Last</li>
								<li></li>
								<li style="padding-right:1px; padding-left: 5px; margin-left: 0px; margin-right: 0px;"><b>Cluster by:</b></li>
								<li><input type="radio" name="sort" onChange="commentsWidget.changeSort(commentsWidget.sort_enum.byRateDesc)">Attitude</li>								
							</ul>

							<div id="comments-container"></div>
							
						</fieldset>
						</div>
						
						<!-- END SECTION: threaded control -->
					</div>
					
					<div id="tabs-2"> <!-- second tab on the paperview page - Citation Information -->
						<div style="float:right; z-index:10;"><a href="help.php#citation" onClick="return popup(this, 'notes')"><img alt="help" src="image/question.png" /></a></div>
						<?php
					    $DOI = DBExecute('SELECT bibtex.doi AS doi
											FROM bibtex WHERE bibtex.id = ?', $paperId);
					   	$DOIRow = $DOI->fetchAssocRow();
					    
					   	$ISBN = DBExecute('SELECT bibtex.isbn AS isbn
											FROM bibtex WHERE bibtex.id = ?', $paperId);
					   	$ISBNRow = $ISBN->fetchAssocRow();
						?>
						<h3> Edit Citation Information </h3><br/>
					    <form name="name" action="controller/editPublication.php" method="post">
							<table>
								<tr><strong><?php echo $_SESSION["errmsg"]; $_SESSION["errmsg"]='';?></strong></tr>
								<tr>
									<td class="labelright"><strong>Title:</strong></td>
									<td><input type="text" name="title" maxlength="200" size="60" value="<?php echo isset($paper['TITLE']) ? htmlentities($paper['TITLE']) : ''; ?>" /></td>
								</tr>
								
								<tr>
									<td class="labelright"><strong>Authors:</strong></td>
									<td><input type="text" name="authors" maxlength="200" size="60" value="<?php echo (isset($paper['AUTHORS'])  && $paper['AUTHORS'] != '') ? htmlentities($paper['AUTHORS']) : (isset($authors['AUTHOR']) ? htmlentities($authors) : ''); ?>" /></td>
								</tr>
								<tr><td></td><td class="labelleft"><font size="1">Separate multiple authors with semicolons</font></td></tr>
								<tr>
									<td class="labelright"><strong>DOI:</strong></td>
									<td><input type="text" name="doi" maxlength="40" size="20" value="<?php echo isset($DOIRow['DOI']) ? htmlentities($DOIRow['DOI']) : ''; ?>" /></td>
								</tr>
								
								<tr>
									<td class="labelright"><strong>ISBN:</strong></td>
									<td><input type="text" name="isbn" maxlength="40" size="20" value="<?php echo isset($ISBNRow['ISBN']) ? htmlentities($ISBNRow['ISBN']) : ''; ?>" /></td>
								</tr>
	
								<tr>
									<td></td>
									<td>
										<input type="hidden" name="submitEdit" value=true/>
										<input type="submit" class="button" value="submit changes" />
									</td>
								</tr>
							</table>
						</form>
					</div>
				</div>
			</div>
		</div>
		<?php include_once 'static/footer.html'; ?>
	</div>
</body>
</html>
